//
//  AddWordController.swift
//  新浪微博项目
//
//  Created by 王炯 on 16/7/26.
//  Copyright © 2016年 王炯. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class AddWordController: UIViewController
{

    
    //懒加载AddWordView
    private lazy var addWord:AddWordView = {
       
        let addV = AddWordView()
        
        addV.delegate = self
        
        //设置站位文字
        addV.placeHolderText = "请输入文字请输入微博文本请输入推文请输入一些文字请输入一些推文"
        
        //设置总体texView的字体大小(包括站位文字的大小)
        addV.font = UIFont.systemFontOfSize(15)
        
        //设置textView的垂直弹簧效果(一定要设置true才有弹簧效果)
        addV.alwaysBounceVertical = true
        
        return addV
        
    }()
    
    //懒加载一个显示图片的collectionView
     private lazy var picView:AddPicCollectionView = AddPicCollectionView()
    
    //懒加载底部View
    private lazy var toolView:AddWordToolView = {
       
        
        let tool = AddWordToolView()
        
        //声明闭包的实现内容
        tool.clickClosure = {[weak self](type:buttonType) ->() in
            
            //根据type信息
            switch(type)
            {
            case .pic:
                //print("图片")
                
                //点击进入到相册，然后选择照片
                self?.PickerUpImageFromALum()
                
            case .emention:
                print("@")
            case .trend:
                print("#")
            case .emotion:
                //print("笑脸")
                
                //点击笑脸之后的触发事件
                self?.EmotionClick()
            case .add:
                print("+")
            }
            
        }
        
        
        return tool
        
    }()
    
    //懒加载一个标题文本，显示用户名的富文本
    private lazy var userTitle:UILabel = {
       
        //设置标题富文本
        //初始化一个富文本
        //用户名
        let userName = AuthViewModel.AuthViewModelTools.userModel?.screen_name ?? ""
        
        let strName = "发微博\n\(userName)"
        
        
        
        let attrStr:NSMutableAttributedString = NSMutableAttributedString(string: strName)
        
        //设置字符串的range
        let range = (strName as NSString).rangeOfString(userName)
        
        //根据range设置富文本
        attrStr.setAttributes([NSForegroundColorAttributeName: UIColor.redColor()], range: range)
        
        //初始化label
        let lab = UILabel()
        
        lab.numberOfLines = 0
        
        lab.textAlignment = .Center
        
        lab.attributedText = attrStr
        
        lab.sizeToFit()
        
        return lab
        
    }()
    
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        //设置界面
        self.setUpUI()
        
        //设置navigationController
        self.setUpNav()
    }

    func setUpUI()
    {
        self.view.backgroundColor = UIColor.whiteColor()
        
        //添加addView
        view.addSubview(self.addWord)
        
        //在addWord上添加picView
        self.addWord.addSubview(self.picView)
        
        //添加toolView到主界面上
        view.addSubview(self.toolView)
        
        
        
        //设置约束
        self.addWord.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        
        self.picView.snp_makeConstraints { (make) in
            make.centerX.equalTo(self.addWord)
            make.top.equalTo(self.addWord).offset(100)
            make.width.height.equalTo(SCREENW-20)
        }
        self.toolView.snp_makeConstraints { (make) in
            make.leading.bottom.trailing.equalTo(self.view)
            make.height.equalTo(44)
        }
        
        
        //实现picView的闭包
        self.picView.closure = {[weak self] () -> () in
            
            self?.PickerUpImageFromALum()
            
        }
        
        
        //监听键盘改变frame的系统通知:UIKeyboardWillChangeFrameNotification
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AddWordController.KeyBordChangeFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        
        //监听删除按钮发来的删除通知命令
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AddWordController.DeleteTextViewText), name: "DeleteText", object: nil)
        
        //监听表情按钮发出的添加表情的通知命令
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AddWordController.AddEmotion(_:)), name: "AddEmotionText", object: nil)
        
        
    }
    
    
    //监听键盘frame改变的系统通知方法
    func KeyBordChangeFrame(noti:NSNotification)
    {
        //print(noti)
        
        
        //获取键盘运动结束时的frame
        guard let info = noti.userInfo else
        {
            return
        }
        
        //info是一个字典
        //(1)获取到info["UIKeyboardFrameEndUserInfoKey"]之后先强转为NSValue
        let value = info["UIKeyboardFrameEndUserInfoKey"] as! NSValue
        
        let AnimationTime = info["UIKeyboardAnimationDurationUserInfoKey"] as! Double
        
        //(2)将value转换成CGRect
        let rect:CGRect = value.CGRectValue()
        
        
        //(3)底部toolBar的移动
        //方法一:
        UIView.animateWithDuration(AnimationTime, animations: {
            
            
            self.toolView.transform = CGAffineTransformMakeTranslation(0, rect.origin.y - SCREENH)
            
            
            }, completion: nil)
        //方法二:
        /*
        self.toolView.snp_updateConstraints { (make) in
            make.bottom.equalTo(self.view).offset(rect.origin.y - SCREENH)
        }
        
        UIView.animateWithDuration(AnimationTime) { 
            self.toolView.layoutIfNeeded()
        }
        */
        
        
    }
    
    
    //实现删除按钮的点击事件
    func DeleteTextViewText()
    {
        //利用textView的退格方法实现删除文本
        //print("删除按钮触发")
        self.addWord.deleteBackward()
    }
    
    //实现表情键盘按钮的点击事件
    func AddEmotion(noti: NSNotification)
    {
        //接收noti中的model信息
        //判断是否可以转换成model对象
        guard let model = noti.object as? EmotionModel else
        {
            return
        }
        
        //判断当前的按钮是emoji按钮还是表情图片按钮
        if model.isEmoji
        {
            //直接将十六进制的字符串转换成emoji表情
            let emojiStr = (model.code ?? "").emoji()
            
            //利用textView的InsertText方法插入文本
            self.addWord.insertText(emojiStr)
        }
        else
        {
            //利用富文本的形式添加表情图片的正常text文本
            //(1)获取当前texView的富文本(可变型富文本)
            let allAttr = NSMutableAttributedString(attributedString: self.addWord.attributedText)
            
            
            
            
            //(2)初始化并设置文本附件(文本附件即表情image)
            //2.1 初始化附件
            let att = MyTextAttachment()
            
            //2.2 设置附件image
            att.image = UIImage(named:model.path ?? "", inBundle: EmotionDataTool.sharedTool.emotionBundle, compatibleWithTraitCollection: nil)
            
            //2.3 设置附件的bounds(一定要)
            //获取textView文本的字体高度
            let lineHeight = self.addWord.font!.lineHeight
            
            //设置y坐标为-4是相对于textView的正常文本位置的y坐标而言向下低于4个位置)
            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
            
            //2.4 利用附件创建一个不可变的富文本
            let attr = NSAttributedString(attachment: att)
            
            //2.5设置附件的model
            att.model = model
            
            
            
            
            
            //(3)获取当前选中的光标位置
            let selectedRange = self.addWord.selectedRange
            
            //(4)利用repalce方法实现将富文本文本添加到光标后
            allAttr.replaceCharactersInRange(selectedRange, withAttributedString: attr)
            //(5)设置富文本的属性(字体大小==textview字体大小)
             allAttr.addAttributes([NSFontAttributeName: self.addWord.font!], range: NSRange(location: 0, length: allAttr.length))
            //(6)重新设置总富文本
            self.addWord.attributedText = allAttr
            //(7)重新设置光标位置(在之前的光标位置上加一)
            self.addWord.selectedRange = NSRange(location: selectedRange.location + 1, length: 0)
            //(8)自动发出系统通知UITextViewTextDidChangeNotification让AddWordView隐藏站位文字!!!!!!
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            
            //(9)自动触发textView的代理方法，使发布按钮显示!!!!!!!
            self.addWord.delegate?.textViewDidChange!(self.addWord)
        }
        
    }
    
    
    func setUpNav()
    {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imageStr: nil, target: self, action: #selector(AddWordController.cancelClick))
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", imageStr: nil, target: self, action: #selector(AddWordController.addSomeContentClick))
        
        //默认发布按钮是不开启的
        navigationItem.rightBarButtonItem?.enabled = false
        
        //设置titleView(有富文本的label）
        navigationItem.titleView = self.userTitle
       
    }
    
    
    //取消按钮，返回上一级
    func cancelClick()
    {
        
        //先取消texView的第一响应
        self.addWord.resignFirstResponder()
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    //发布信息触发事件
    func addSomeContentClick()
    {
        
        
        //定义一个可变的字符
        var status:String = ""
        
        
        
        //遍历textView的富文本
        //(1)range：整个富文本的范围，开始位置0.长度为富文本长度
        //(2)options:默认传入空数组
        
        //(1)遍历的结果
        //(2)遍历的范围
        //(3)遍历是否停止
        //在遍历过程中当遇到富文本附件时，将富文本对应的图片根据model转换成model的文字
        //故需要自定义富文本附件，在其中加入一个model属性，用于富文本图片转文字
        self.addWord.attributedText.enumerateAttributesInRange(NSRange(location: 0,length:self.addWord.attributedText.length), options: []) { (result, range,_) in
            
            
            //取result字典中的富文本附件!!!!!!!!!!
            //如果有富文本附件时
            if let att = result["NSAttachment"] as? MyTextAttachment
            {
                //利用att的图片转成文字(利用model属性)
                status += att.model?.chs ?? ""
                
            }
            //如果没有富文本附件时(普通的字符文本)
            else
            {
                //字符串截取(从富文本截取)
                let str = (self.addWord.attributedText.string as
NSString).substringWithRange(range)
                
                status += str
            }
        }
        
        //判断collectionView中有没有图片，来调用不同的方法
        if self.picView.dataArray.count > 0
        {
            self.SendPic(status)
        }
        else
        {
            self.SendWord(status)
        }
    }
    
    
    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
    }
    
    
    deinit
    {
        //将监听移除
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    

}

//实现AddWordView的代理方法
extension AddWordController:UITextViewDelegate
{
    //实现textView的代理方法,监控输入情况
    func textViewDidChange(textView: UITextView)
   {
         //textView有数据时，rightBarButtonItem开启
         navigationItem.rightBarButtonItem?.enabled  = textView.hasText()

   }
    
   //UITextViewDelegate继承自UIScrollViewDelegate，可以实现UIScrollViewDelegate的一些代理方法
    func scrollViewDidScroll(scrollView: UIScrollView)
    {
        //当拖动textView时，取消输入框的第一响应者身份
        self.addWord.resignFirstResponder()
    }
}


extension AddWordController: UIImagePickerControllerDelegate,UINavigationControllerDelegate
{
    
    //点击进入相册界面，选择界面
    func PickerUpImageFromALum()
    {
        //进入到相册，选择照片
        let picker = UIImagePickerController()
        
        picker.delegate = self
        
        //显示相册
        self.presentViewController(picker, animated: true, completion: nil)
    }
    
    //点击选择照片之后的代理方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?)
    {
        
        //将获取之后的图片赋值给collectionView的图片数组
        picView.AddImageToArray(image.miniNumPic(600))
        
        //相册消失
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
        
}

//在此扩展中定义一些点击底部按钮的触发事件
extension AddWordController
{
    //点击笑脸之后的触发事件
    func EmotionClick()
    {
        
        if toolView.isEmotion
        {
            toolView.isEmotion = false
            
            //显示系统键盘
            //设置inputView为nil
            self.addWord.inputView = nil
        }
        else
        {
            toolView.isEmotion = true
            
            //显示表情键盘
            self.addWord.inputView = EmotionKeyBordView(frame:CGRect(x: 0, y: 0, width: SCREENW, height: 216))
        }
        
        //刷新textView的inputView
        self.addWord.reloadInputViews()
        
        //设置textView为第一响应者
        self.addWord.becomeFirstResponder()
        
    }
}
//发送微博
extension AddWordController
{
    //1-发送文字微博
    func SendWord(status:String)
    {
        //(1)请求的urlString
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        
        
        //(2)参数
        let param = ["access_token":AuthViewModel.AuthViewModelTools.accessToken ?? "",
                     "status":status]
        
        //(3)发送请求:POST请求
        WeiBoNetWorkTool.sharedTools.PostWebData(urlString, parameters: param, successCallBack: { (response) in
            
            SVProgressHUD.showSuccessWithStatus("发送成功")
            
            
            }) { (error) in
                
            SVProgressHUD.showErrorWithStatus("发送失败")
                
        }
    }
    //2-发送图片微博
    func SendPic(status:String)
    {
           WeiBoNetWorkTool.sharedTools.composeUpload(status, imageList: self.picView.dataArray, success: { (response) in
            
            
            SVProgressHUD.showSuccessWithStatus("发送成功")
            
            
            }) { (error) in
                
                
                
             SVProgressHUD.showErrorWithStatus("发送失败")
                
                
        }
        
    }
    
    
}

